//
//  HOQuickReportViewController.m
//  WeiDu_1_0
//
//  Created by foguo-mac-1 on 01/07/16.
//  Copyright (c) 2016 WeiDu Energy Tech. All rights reserved.
//

#import "HOQuickReportViewController.h"
#import "HOUtils.h"
#import "HOEditView.h"
#import <AVFoundation/AVFoundation.h>
#import "HOUtils.h"
#import "HODefine.h"
#import "HOReportViewController.h"
#import "HODepartmentViewController.h"
#import "HOFaultCategoryViewController.h"
#import "HODepartmentViewController.h"
#import "HODepartmentEntity.h"
#import "GTMBase64.h"
#import "HOConstants.h"
#import "HOStaticDataMgr.h"
#import "HOAreaEntity.h"
#import "HOHybridTypeViewController.h"

@interface HOQuickReportViewController()<UIAlertViewDelegate, HOHybridTypeViewControllerDelegate>
{

}
@property(nonatomic, assign)int faultId;
@property(nonatomic, assign)int departmentId;
@end

@implementation HOQuickReportViewController
- (void)viewDidLoad
{
	[super viewDidLoad];
	[self initDataSource];
	[self initTableView];
	[self initSubviews];
	[self initMediaView];
	[self registerKeyboard];
	[self registerTapGesture];
	
//	[self initReportDepartment];
	[self initReportAreaFromLocal];
}

- (void)initDataSource
{
}

- (void)initSubviews
{
	baseTableview.tableFooterView = [self getFooterViewWithTitle:@"提交"];
}

- (void)didClickFooterButton:(UIButton *)btn
{
	
	if(self.selectedFirstAreaEntity == nil || self.selectedSecondAreaEntity == nil)
	{
		[self popupHintView:NSLocalizedString(@"请选择报修地点！", @"请选择报修地点！")];
		return;
	}
	
	if(![self isSelectFaultType:btn])
		return;
	[self convertingVoice];

}

- (void)submit
{
	[super submit];
	if(self.selectedSubFaultGategoryEntity == nil
	   || self.selectedFaultGategoryEntity == nil)
	{
		[self popupHintView:NSLocalizedString(@"请选择故障分类！", @"请选择故障分类！")];
		return;
	}
	
	NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:[super getMediaDic]];
	NSString *image = [dic objectForKey:kHO_FIELD_FaultImage];
	NSString *data = [dic objectForKey:kHO_FIELD_FaultVoice];
	
	if((image == nil || image.length == 0) && (data == nil || data.length == 0))
	{
		[self popupHintView:NSLocalizedString(@"无语音或图片信息，请提交!", @"无语音或者图片信息，请提交!") inTime:2.5];
		return;
	}
	
	[dic setObject:[self getSelectArea] forKey:kHO_FIELD_AreaId];
	
	[dic setObject:kHO_ACTION_AddNormalReport forKey:kHO_FIELD_Action];
	NSString *faultDetail = [self getTrimingCharaFromTextView:[self.reportDescEditView getTextView]];
	[dic setObject:[HOUtils getValideString:faultDetail] forKey:kHO_FIELD_FaultDetail];
	[dic setObject:[NSNumber numberWithInt:self.selectedDepartmentEntity.departmentId] forKey:kHO_FIELD_DepartmentId];

	NSString *faultId = [NSString stringWithFormat:@"%d-%d", self.selectedFaultGategoryEntity.faultId, self.selectedSubFaultGategoryEntity.faultId];
	[dic setObject:faultId forKey:kHO_FIELD_FaultId];
	[dic setObject:[NSNumber numberWithBool:YES] forKey:kHO_FIELD_Isurgent];
	[self sendRequestWithParams:dic];
}
#pragma mark -- keyboard
- (void)onKeyboardWillShow:(NSNotification *)notification
{
	[super onKeyboardWillShow:notification];
	[baseTableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
	[self hideKeyboard];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
	[self hideKeyboard];
}

- (void)viewWillAppear:(BOOL)animated
{
	self.tabBarController.tabBar.hidden = NO;
	self.navigationItem.hidesBackButton = YES;
	[super viewWillAppear:animated];
	[self.reportDescEditView getTextView].text = @"无";
	[self setNavigationItemTitle:NSLocalizedString(@"紧急报修", "紧急报修")];
	
	if(![[[HOStaticDataMgr sharedInstance] getUserInfo] isReportUser])
	{
		[self displayRightButtonItemWithTitle:NSLocalizedString(@"普通报修", @"普通报修")];
	}
	else
	{
		[self displayRightButtonItemWithTitle:NSLocalizedString(@"重置", @"重置")];
	}
	[self resetTableViewFrame];
	[baseTableview reloadData];
}

- (void)rightButtonItemDidClick
{
	if(![[[HOStaticDataMgr sharedInstance] getUserInfo] isReportUser])
	{
		HOReportViewController *viewCtrl = [[HOReportViewController alloc] init];
		[self.navigationController pushViewController:viewCtrl animated:YES];
		[viewCtrl release];
	}
	else
	{
		[self cleanup];
	}
}

#pragma mark - -- UITableViewDelegate/UITableViewDataResource implement methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(indexPath.section == 0)
		return 44;
	else if(indexPath.section == 1)
	{
		CGFloat contentDisplayWidth = tableView.frame.size.width - 120;
		
		NSString *deptName = [HOUtils getValideString:self.selectedDepartmentEntity.departmentName];
		NSString *typeName = [self getSelectTypeNames];
		NSString *content = @"";
		if([HOUtils getValideString:deptName].length == 0 || [HOUtils getValideString:typeName].length == 0)
		{
			content = @"请点击选择";
		}
		else
		{
			content = [NSString stringWithFormat:@"[%@]-%@", deptName, typeName];
		}
		
		CGSize contentSize = CGSizeZero;
		if(IS_LESSTHAN_IOS7)
		{
			contentSize = [HOUtils findHeightForText:content havingWidth:contentDisplayWidth andFont:[UIFont systemFontOfSize:14]];
		}
		else
		{
			contentSize = [HOUtils findHeightForText:content havingWidth:contentDisplayWidth andFont:[UIFont systemFontOfSize:15]];
		}
		CGFloat height = MAX(22, contentSize.height);
		return height + 15;
	}
	else if(indexPath.section == 2)
	{
		if(indexPath.row == 1)
		{
			return [self getPhotoViewHeight];
		}
		else
		{
			return self.isRecordModal ?  50 + 128 + 22 : 50;
		}
	}
	return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	if(section == 0)
		return 1;
	if(section == 1)
		return 1;
	else if(section == 2)
		return 2;
    return 0;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	if(section == 0 || section == 1)
		return 0.001;
	else if(section == 2)
		return SECTION_PADDING / 2;
	return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *AMBaseTableViewCellIdentifier = @"HOTableViewCell";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:AMBaseTableViewCellIdentifier];
    if(cell == nil)
    {
        cell = [[[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier: AMBaseTableViewCellIdentifier] autorelease];
    }
	CGFloat cellHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
	cell.textLabel.font = [UIFont systemFontOfSize:15];
	cell.textLabel.textColor = TEXT_COLOR_181818;
	UILabel *detailLbl = (UILabel *)[cell viewWithTag:114];
	if(detailLbl)
		detailLbl.hidden = YES;
	if(indexPath.section == 0)
	{
		if(detailLbl == nil)
		{
			detailLbl = [[[UILabel alloc]
						  initWithFrame:CGRectMake(90,
												   (cellHeight - 22) / 2,
												   tableView.frame.size.width - 120,
												   22)] autorelease];
			detailLbl.tag = 114;
			detailLbl.font = [UIFont systemFontOfSize:15];
			detailLbl.textColor = TEXT_COLOR_666666;
			[cell.contentView addSubview:detailLbl];
		}
		detailLbl.hidden = NO;
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		cell.selectionStyle = UITableViewCellSelectionStyleDefault;
		if(indexPath.row == 0)
		{
			cell.textLabel.text = NSLocalizedString(@"报修地点", @"报修地点");
			detailLbl.numberOfLines = 2;
			detailLbl.frame = CGRectMake(90,
										 (cellHeight - detailLbl.frame.size.height) / 2,
										 tableView.frame.size.width - 120,
										 100);
			detailLbl.text = [self getSelectAreaName];
			[detailLbl sizeToFit];
			detailLbl.frame = CGRectMake(90,
										 (cellHeight - detailLbl.frame.size.height) / 2,
										 tableView.frame.size.width - 120,
										 detailLbl.frame.size.height);
		}
	}
	else if(indexPath.section == 1)
	{
		if(detailLbl == nil)
		{
			detailLbl = [[[UILabel alloc]
								  initWithFrame:CGRectMake(90,
														   (cellHeight - 22) / 2,
														   tableView.frame.size.width - 120,
														   22)] autorelease];
			detailLbl.tag = 114;
			detailLbl.font = [UIFont systemFontOfSize:15];
			detailLbl.textColor = TEXT_COLOR_666666;
			[cell.contentView addSubview:detailLbl];
		}
		detailLbl.hidden = NO;
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		cell.selectionStyle = UITableViewCellSelectionStyleDefault;
		if(indexPath.row == 0)
		{
			cell.textLabel.text = NSLocalizedString(@"故障分类", @"故障分类");
			NSString *deptName = [HOUtils getValideString:self.selectedDepartmentEntity.departmentName];
			NSString *typeName = [self getSelectTypeNames];
			if([HOUtils getValideString:deptName].length == 0 || [HOUtils getValideString:typeName].length == 0)
			{
				detailLbl.text = @"请点击选择";
				detailLbl.textAlignment = NSTextAlignmentRight;
			}
			else
			{
				detailLbl.text = [NSString stringWithFormat:@"[%@]-%@", deptName, typeName];
				detailLbl.textAlignment = NSTextAlignmentLeft;
			}
			detailLbl.frame = CGRectMake(90,
										 (cellHeight - detailLbl.frame.size.height) / 2,
										 tableView.frame.size.width - 120,
										 100);
			detailLbl.numberOfLines = 2;
			[detailLbl sizeToFit];
			detailLbl.frame = CGRectMake(90,
										 (cellHeight - detailLbl.frame.size.height) / 2,
										 tableView.frame.size.width - 120,
										 detailLbl.frame.size.height);
		}
	}
	else if(indexPath.section == 2)
	{
		return [self tableView:tableView cellForQuickTakePhotoRowAtIndexPath:indexPath];

	}
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
	if(indexPath.section == 0)
	{
		HOReportLocationViewController *viewCtrl = [[HOReportLocationViewController alloc] init];
		viewCtrl.delegate = self;
		viewCtrl.selectedFirstAreaEntity = self.selectedFirstAreaEntity;
		viewCtrl.selectedSecondAreaEntity = self.selectedSecondAreaEntity;
		viewCtrl.selectedThirdAreaEntity = self.selectedThirdAreaEntity;
//		[viewCtrl initSearchBar];
		[self.navigationController pushViewController:viewCtrl animated:YES];
		[viewCtrl release];
	}
	else if(indexPath.section == 1)
	{
//		[super didSelectForDepartmentRowAtIndexPath:indexPath];
		HOHybridTypeViewController *viewCtrl = [[HOHybridTypeViewController alloc] init];
		viewCtrl.delegate = self;
		viewCtrl.currentEntity = self.selectedFaultGategoryEntity;
		viewCtrl.subEntity = self.selectedSubFaultGategoryEntity;
		viewCtrl.currentDepartmentEntity = self.selectedDepartmentEntity;
		[self.navigationController pushViewController:viewCtrl animated:YES];
		[viewCtrl release];
	}
}

- (void)cleanup
{
	[super cleanup];
	[self hideKeyboard];
	[baseTableview reloadData];
}
#pragma mark -- request result.
- (void)requestDidSuccessWithResponse:(HOBaseResponseEntity *)response
{
	if([response isEqualAction:kHO_ACTION_AddNormalReport])
	{
		[self cleanup];
		[self sendCommand:kHO_CMD_Report_List_Changed data:nil];
		[self sendCommand:kHO_CMD_Report_Clear_Report data:nil];
		[baseTableview reloadData];
		[self didSubmitReport];
	}
}

@end
